問題很簡單,就是反轉一個 Linked List.
https://leetcode.com/problems/reverse-linked-list/
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
在 Go 語言,每個變數都要有對應的資料格式,通常我們會使用類型推斷(Type Inference)來宣告變數並給予初始值,譬如:message := "Hello World"
.
但如果要宣告一個變數為 nil 值時,則無法使用Type Inference.
所以這個語法previous := nil
是錯誤的.
必須將對應的資料格式一起宣告 var previous *ListNode = nil
.
使用三個指標:
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
previous = None
current = head
while current:
head = head.next
current.next = previous
previous = current
current = head
return previous
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
var previous *ListNode = nil
var current *ListNode = head
for current != nil {
head = head.Next
current.Next = previous
previous = current
current = head
}
return previous
}